from infra.handler import BaseHandler
from .auth_db import create_user_auth, get_user_auth_status, update_auth_status
from common.tencent_ocr import recognize_id_card
from domain.message.message_db import insert_message  # 导入消息插入函数
import json,os,base64
from datetime import datetime
def  file_to_base64(file_path):
    with open(file_path, 'rb') as file:
        image_data = file.read()
        base64_encoded = base64.b64encode(image_data).decode('utf-8')
        return base64_encoded
def is_id_card_valid(valid_date_str):
    """
    判断身份证是否在有效期内
    
    :param valid_date_str: 身份证有效期字符串，格式如：2022.04.12-2042.04.12
    :return: 是否在有效期内，True或False
    """
    try:
        # 分割起始日期和结束日期
        date_parts = valid_date_str.split('-')
        if len(date_parts) != 2:
            return False
            
        start_date_str, end_date_str = date_parts
        
        # 解析日期字符串为datetime对象
        start_date = datetime.strptime(start_date_str.strip(), '%Y.%m.%d')
        
        # 处理特殊情况：如果结束日期是"长期"，则视为永久有效
        if end_date_str.strip() == "长期":
            end_date = datetime.max
        else:
            end_date = datetime.strptime(end_date_str.strip(), '%Y.%m.%d')
        
        # 获取当前日期
        current_date = datetime.now()
        # 判断当前日期是否在有效期内
        return start_date <= current_date <= end_date
    except Exception as e:
        print(f"解析身份证有效期出错: {str(e)}")
        return False

class UserAuthHandler(BaseHandler):
    async def post(self):
        """提交实名认证信息"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "用户未登录"}))
                return
            data = json.loads(self.request.body)
            id_front_url = data.get('id_front_url')
            id_back_url = data.get('id_back_url')
            if '?filename=' in id_front_url:
                front_name = id_front_url.split('?filename=')[-1]
                front_name= os.path.join("uploads", front_name)

            if '?filename=' in id_back_url:
                # 提取filename部分
                back_name = id_back_url.split('?filename=')[-1]
                back_name= os.path.join("uploads", back_name)

            # 验证必填字段
            if not all([id_front_url, id_back_url]):
                self.write(json.dumps({"code": 404, "msg": "缺少必要信息"}))
                return
            base64_front = file_to_base64(front_name)
            result = recognize_id_card(base64_front, "FRONT")
            result = json.loads(result)
            real_name = result.get('Name')
            id_number = result.get('IdNum')
            sex = result.get('Sex')
            if(not real_name or not id_number or not sex):
                self.write(json.dumps({"code": 404, "msg": "身份证信息识别失败"}))
                return
            if(sex == "男"):
                self.write(json.dumps({"code": 404, "msg": "禁止男性实名认证"}))
                return
            base64_back = file_to_base64(back_name)
            result = recognize_id_card(base64_back, "BACK")
            result = json.loads(result)
            valid_date = result.get('ValidDate')
            if(not valid_date):
                self.write(json.dumps({"code": 404, "msg": "身份证信息识别失败"}))
                return
            # 判断身份证是否在有效期内
            if not is_id_card_valid(valid_date):
                self.write(json.dumps({"code": 404, "msg": "身份证已过期，请使用有效期内的身份证"}))
                return

            success, msg, auth_id = await create_user_auth(
                user_id, real_name, id_number, id_front_url, id_back_url
            )
            success, _ = await update_auth_status(auth_id, 1)
            if success:
                # 发送认证成功的系统消息
                message_title = "实名认证结果通知"
                message_content = f"恭喜您，您的实名认证已通过审核。认证姓名：{real_name}"
                await insert_message(
                    type="system",
                    title=message_title,
                    content=message_content,
                    receiver_id=user_id
                )
                self.write(json.dumps({"code": 200, "msg": msg}))
            else:
                # 发送认证失败的系统消息
                message_title = "实名认证结果通知"
                message_content = f"很抱歉，您的实名认证未通过审核。原因：{msg}"
                await insert_message(
                    type="system",
                    title=message_title,
                    content=message_content,
                    receiver_id=user_id
                )
                self.write(json.dumps({"code": 404, "msg": msg}))

        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))

    async def get(self):
        """获取认证状态"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "用户未登录"}))
                return

            success, data = await get_user_auth_status(user_id)
            
            if success:
                self.write(json.dumps({"code": 200, "data": data}))
            else:
                self.write(json.dumps({"code": 404, "msg": data["msg"]}))

        except Exception as e:
            self.write(json.dumps({"code": 500, "msg": str(e)}))
